package com.wish.wishfinancial_service.controller;


import com.github.pagehelper.PageHelper;
import com.wish.wishfinancial_service.entity.TFkBusinessCredit;
import com.wish.wishfinancial_service.entity.TJrProduct;
import com.wish.wishfinancial_service.mapper.TFkBusinessCreditMapper;
import com.wish.wishfinancial_service.mapper.TJrProductMapper;
import com.wish.wishfinancial_service.service.ITFkBusinessCreditService;
import com.wish.wishfinancial_service.service.ITJrProductService;
import com.wish.wishfinancial_service.service.ITJrSfLoanService;
import com.wish.wishfinancial_service.service.ITSfContractService;
import com.wish.wishfinancial_service.service.feignservice.HouseServiceFeign;
import dto.financialResponse.SearchSfLoanDetailsResponseDto;
import dto.financialResponse.SfContractDetailsResponseDTO;
import dto.financialservice.*;
import dto.houseForeclosureDto.RequestSearchSfsDto;
import form.SaveSfLoanForm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import vo.ResultEntity;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 收房贷申请信息 前端控制器
 * </p>
 *
 * @author weijiaz
 * @since 2021-04-10
 */
@RestController
@RequestMapping("/tJrSfLoan")
public class TJrSfLoanController {

    @Autowired
    private ITJrSfLoanService itJrSfLoanService;
    @Autowired
    private HouseServiceFeign houseServiceFeign;

    @Autowired
    private ITSfContractService itSfContractService;

    @Autowired
    private TJrProductMapper tJrProductMapper;
    @Autowired
    private ITFkBusinessCreditService itFkBusinessCreditService;
    @Autowired
    private TFkBusinessCreditMapper tFkBusinessCreditMapper;



    /**
     * 申请收房贷：计算--分期
     * @return
     */
    @RequestMapping("listSfLoan")
    public ResultEntity listSfLoan(SfLoanDetailRequestBean bean){
        HashMap<String, Object> map = new HashMap<>();
        // 收房贷计算
        SfContractDetailsResponseDTO sfentity = itSfContractService.getSfContractStagingCalculation(bean.getContractId(),bean.getProductId());

        SearchSfLoanDetailRequestDto sfdto = new SearchSfLoanDetailRequestDto();

        BeanUtils.copyProperties(bean,sfdto);

        sfdto.setBalance(Double.parseDouble(bean.getBalance()));	// 借款金额
        sfdto.setSxBalance(Double.parseDouble(bean.getSxBalance())); // 授信额
        sfdto.setPeriods(bean.getPeriods());	// 期数
        sfdto.setStartDate(bean.getStartDate()); // 合同开始日
        sfdto.setEndDate(bean.getEndDate());	// 合同结束日
        // 分期计算
        SearchSfLoanDetailsResponseDto sfr= itJrSfLoanService.getSfLoanDetail(sfdto);
        map.put("dataList",sfr);
        map.put("sfentity",sfentity);
        return ResultEntity.ok(map);
    }

    /**
     * 申请收房贷：保存
     * @return
     */
    @RequestMapping("savesf")
    public ResultEntity saveContract(SaveSfLoanForm sfLoanForm){

        if(sfLoanForm.getPeriods() > sfLoanForm.getPeriodsA()) {
            return ResultEntity.error("借款期限大于合同有效期限");
        }

        SaveSfLoanRequestDto sd = new SaveSfLoanRequestDto();
        BeanUtils.copyProperties(sfLoanForm, sd);
        TJrProduct jrProduct = tJrProductMapper.selectById(sd.getProductId());
        if(jrProduct.getInstalmentPeriod() < sfLoanForm.getPeriods()) {
            return ResultEntity.error("借款期限大于金融产品期限");
        }

        TFkBusinessCredit objectBusiness = this.itFkBusinessCreditService.queryObjectBusinessId(sd.getBusinessId());
        //去查询是否给该商户授权了该产品
        ViewDetailsRequestDto viewDetailsRequestDto = new ViewDetailsRequestDto();
        viewDetailsRequestDto.setBusinessId(sd.getBusinessId());
        viewDetailsRequestDto.setProductId(sfLoanForm.getProductId());
        ZJFInformation findById = this.itFkBusinessCreditService.findByBusinessAndProductId(viewDetailsRequestDto);
        //未给该商户授权该产品
        if(findById == null) {
            return ResultEntity.error("授信额度不足，请联系维数公寓客服：400-008-3363");
        }
        BigDecimal subtractProduct = BigDecimal.ZERO;
        //商户该产品总授信额度减该产品已用授信额度
        if(findById.getUsedCreditline() != null && !findById.getUsedCreditline().equals(BigDecimal.ZERO)) {
            subtractProduct = findById.getTotalCreditline().subtract(findById.getUsedCreditline());
        } else {
            subtractProduct = findById.getTotalCreditline();
        }
        //申请分期金额大于该商户中的该产品剩余授信金额
        if(sfLoanForm.getSxBalance().compareTo(subtractProduct) == 1) {
            return ResultEntity.error("授信额度不足，请联系维数公寓客服：400-008-3363");
        }
        if(findById.getMonthlyTotalCreditline() != null && !findById.getMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            //商户总授信额度减已用授信额度
            BigDecimal subtractMonthly = BigDecimal.ZERO;
            if(findById.getMonthlyUsedCreditline() != null && !findById.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                subtractMonthly = findById.getMonthlyTotalCreditline().subtract(findById.getMonthlyUsedCreditline());
            } else {
                subtractMonthly = findById.getMonthlyTotalCreditline();
            }
            //申请分期金额大于该商户月剩余授信金额
            if(sfLoanForm.getSxBalance().compareTo(subtractMonthly) == 1) {
                return ResultEntity.error("授信额度不足，请联系维数公寓客服：400-008-3363");
            }
        }else {
            if(objectBusiness.getHlMonthlyTotalCreditline() != null && !objectBusiness.getHlMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
                //商户月授信额度减月已用授信额度
                BigDecimal subtractMonthly = BigDecimal.ZERO;
                if(objectBusiness.getHlMonthlyUsedCreditline() != null && !objectBusiness.getHlMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                    subtractMonthly = objectBusiness.getHlMonthlyTotalCreditline().subtract(objectBusiness.getHlMonthlyUsedCreditline());
                } else {
                    subtractMonthly = objectBusiness.getHlMonthlyTotalCreditline();
                }
                //申请分期金额大于该商户月剩余授信金额
                if(sfLoanForm.getSxBalance().compareTo(subtractMonthly) == 1) {
                    return ResultEntity.error("授信额度不足，请联系维数公寓客服：400-008-3363");
                }
            }
        }

        BigDecimal hlUsedCreditline = BigDecimal.ZERO;
        if(objectBusiness.getHlUsedCreditline() != null && !objectBusiness.getHlUsedCreditline().equals(BigDecimal.ZERO)) {
            hlUsedCreditline = objectBusiness.getHlUsedCreditline().add(sfLoanForm.getSxBalance());
        } else {
            hlUsedCreditline = sfLoanForm.getSxBalance();
        }
        objectBusiness.setHlUsedCreditline(hlUsedCreditline);
        if(objectBusiness.getHlMonthlyTotalCreditline() != null && !objectBusiness.getHlMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            BigDecimal hlMonthlyUsedCreditline = BigDecimal.ZERO;
            if(objectBusiness.getHlMonthlyUsedCreditline() != null && !objectBusiness.getHlMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                hlMonthlyUsedCreditline = objectBusiness.getHlMonthlyUsedCreditline().add(sfLoanForm.getSxBalance());
            } else {
                hlMonthlyUsedCreditline = sfLoanForm.getSxBalance();
            }
            objectBusiness.setHlMonthlyUsedCreditline(hlMonthlyUsedCreditline);
        }
        objectBusiness.setUpdateTime(new Date());
        objectBusiness.setUpdateUserid(sd.getLoginUserId());
        this.itFkBusinessCreditService.updateById(objectBusiness);


        BigDecimal usedCreditlineProduct = BigDecimal.ZERO;
        if(findById.getUsedCreditline() != null && !findById.getUsedCreditline().equals(BigDecimal.ZERO)) {
            usedCreditlineProduct = findById.getUsedCreditline().add(sfLoanForm.getSxBalance());
        } else {
            usedCreditlineProduct = sfLoanForm.getSxBalance();
        }
        findById.setUsedCreditline(usedCreditlineProduct);
        if(findById.getMonthlyTotalCreditline() != null && !findById.getMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            BigDecimal hlMonthlyUsedCreditline = BigDecimal.ZERO;
            if(findById.getMonthlyUsedCreditline() != null && !findById.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                hlMonthlyUsedCreditline = findById.getMonthlyUsedCreditline().add(sfLoanForm.getSxBalance());
            } else {
                hlMonthlyUsedCreditline = sfLoanForm.getSxBalance();
            }
            findById.setMonthlyUsedCreditline(hlMonthlyUsedCreditline);
        }
        findById.setUpdateUserid(sd.getLoginUserId());
        this.tFkBusinessCreditMapper.updateFkBusinessCreditSub(findById);

        itJrSfLoanService.saveLoan(sd);
        // 保存识别码
//		businessOutUuidService.saveOrUpdateBusinessOutUuid(sfLoanForm.getProductId(), sfLoanForm.getBusinessOutUuid());
        return ResultEntity.ok();
    }



}

